package generator

import (
	"fmt"
	"os"
	"sql2entity/parser"
	"sql2entity/tmpl"
	"sql2entity/util"
	"text/template"
)

// GenerateGoCode 生成Go语言代码
func GenerateGoCode(sql, tmplText string, outPath string) error {
	tableInfo := parser.GetTableInfoFromSql(sql)
	goTmpl := template.New("goStruct").Funcs(template.FuncMap{
		"Underline2BigCamelCase": util.Underline2BigCamelCase,
		"GetGoType":              GetGoType,
	})
	if tmplText != "" {
		goTmpl = template.Must(goTmpl.Parse(tmplText))
	} else {
		goTmpl = template.Must(goTmpl.Parse(tmpl.GoStructTmpl))
	}
	fp, err := os.OpenFile(fmt.Sprintf("%s/%s.go", outPath, tableInfo.TableName), os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	err = goTmpl.Execute(fp, tableInfo)
	if err != nil {
		return err
	}
	return nil
}

// sqlType2GoType MySQL中类型和Go中类型对应关系
var sqlType2GoType = map[string]string{
	"tinyint":    "int8",
	"smallint":   "int16",
	"mediumint":  "int",
	"int":        "int",
	"integer":    "int",
	"bigint":     "int64",
	"float":      "float32",
	"double":     "float64",
	"decimal":    "float64",
	"date":       "time.Time",
	"time":       "time.Time",
	"year":       "time.Time",
	"datetime":   "time.Time",
	"timestamp":  "time.Time",
	"char":       "string",
	"varchar":    "string",
	"tinyblob":   "[]byte",
	"tinytext":   "string",
	"blob":       "[]byte",
	"text":       "string",
	"mediumblob": "[]byte",
	"mediumtext": "string",
	"longblob":   "[]byte",
	"longtext":   "string",
}

// GetGoType 根据MySQL中类型获取Go语言中的类型
func GetGoType(sqlType string) string {
	return sqlType2GoType[sqlType]
}
